package com.zhiyuancode.mqack.worker.recorder;

import com.zhiyuancode.mqack.message.base.MqResendErrorCode;
import com.zhiyuancode.mqack.message.base.MqResendRuntimeException;
import com.zhiyuancode.mqack.message.base.addressAndMessage.BaseAddressAndMessage;
import com.zhiyuancode.mqack.message.base.message.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ZSetOperations;

import java.io.IOException;
import java.util.List;

import static com.zhiyuancode.mqack.worker.Constants.RESEND_MSG_ID_COL;
import static com.zhiyuancode.mqack.worker.Constants.RESEND_MSG_PREFIX;


/**
 * @author 杨志远
 * email faryangsh@163.com
 * Date    2018-05-15
 */
@Slf4j
public abstract class BaseRecorder {
    protected ZSetOperations<String, String> zSetOperations;
    protected HashOperations<String, String, String> hashOperations;

    /**
     * 删除要已发的MQ记录
     */
    public void deleteMessageRecord(Message message) {
        String msgId = message.acquireMsgId();
        deleteMessageRecord(msgId);
    }

    /**
     * 消息Id
     *
     * @param msgId
     */
    protected void deleteMessageRecord(String msgId) {
        try {
            // 删除消息记录
            zSetOperations.remove(RESEND_MSG_ID_COL, msgId);
            // 删除消息内容
            hashOperations.getOperations().delete(RESEND_MSG_PREFIX + msgId);
        } catch (RedisConnectionFailureException e) {
            log.error("failed delete message record: msgId={},e={}", msgId, e.getMessage());
            throw new MqResendRuntimeException(MqResendErrorCode.REDIS_CONNECTION_EXCEPTION, e);
        } catch (Throwable e) {
            log.error("failed delete message record: msgId={},e={}", msgId, e.getMessage());
            throw new MqResendRuntimeException(MqResendErrorCode.UNKNOW_EXCEPTION, e);
        }
    }

    /**
     * 查询待重发的消息
     *
     * @return
     */
    public abstract List<? extends BaseAddressAndMessage> queryResendMessage() throws IOException;

    public abstract Class getMessageClass();
}
